import bpy
from bpy.props import BoolProperty, FloatProperty, IntProperty
from bpy.types import UIList

from ..ops import asset
from ..utils.preferences import Preferences


def space_layout(layout: 'bpy.types.UILayout', space: int, level: int) -> 'bpy.types.UILayout':
    """
    设置间隔
    """
    if level == 0:
        return layout.column()
    indent = level * space / bpy.context.region.width

    split = layout.split(factor=indent)
    split.column()
    return split.column()


class AssetTree(UIList, Preferences):
    bl_idname = 'UI_UL_DRAW_RENDER_MASTER_ASSET_TREE'
    use_filter_show: BoolProperty(default=True)
    show_folder: BoolProperty()
    space_size: IntProperty(default=15,
                            min=1,
                            max=40,
                            name='间隔',
                            )

    split_size: FloatProperty(min=0.01,
                              max=0.99,
                              default=0.95,
                              name='拆分大小',
                              )

    use_filter_name_reverse: bpy.props.BoolProperty(
        name='Reverse Name',
        default=False,
        description='Reverse name filtering',
    )

    @property
    def show_selected(self) -> bool:
        """反回是否显示选择整个文件夹的布尔值"""
        pool = self.pref.is_pool_mode and (not self.is_show_render_queue)
        obj = self.pref.is_object_mode and self.is_show_scene
        scene = self.pref.is_scene_mode and self.is_show_object
        return pool or obj or scene

    def draw_item(self,
                  context: 'bpy.context',
                  layout: 'bpy.types.UILayout',
                  data: 'AnyType',
                  item: 'AnyType',
                  icon: int,
                  active_data: 'AnyType',
                  active_property: str,
                  index: int = 0,
                  flt_flag: int = 0):
        split = layout.split(factor=self.split_size, align=True)

        # A
        space = space_layout(split, self.space_size, item.level)
        row = space.row(align=True)

        if item.have_child_folder:
            row.prop(item, 'show_child',
                     text='',
                     toggle=True,
                     icon='FILE_FOLDER' if item.show_child else 'FILE_TICK')
        row.label(text=item.folder_name)

        # B
        ro = split.row(align=True)
        if self.show_selected:
            ro.prop(item, 'selected',
                    text='',
                    toggle=False,
                    emboss=0,
                    icon='RESTRICT_SELECT_OFF' if item.selected else 'RESTRICT_SELECT_ON')
        else:
            ...

    def draw_filter(self, context: 'bpy.context', layout: 'bpy.types.UILayout'):
        column = layout.column()

        row = column.row(align=True)

        sub_row = row.row(align=True)
        sub_row.prop(self, 'filter_name')
        sub_row.prop(self, 'use_filter_invert',
                     icon='ARROW_LEFTRIGHT',
                     toggle=True,
                     icon_only=True,
                     )
        if not (self.use_filter_sort_lock and self.bitflag_filter_item):
            sub_row = sub_row.row(align=True)
            sub_row.prop(self, 'use_filter_sort_alpha',
                         toggle=True,
                         icon_only=True,
                         )

            icon = 'SORT_DESC' if (
                    self.bitflag_filter_item and self.use_filter_sort_reverse) else 'SORT_ASC'

            sub_row.prop(self, 'use_filter_sort_reverse',
                         icon=icon,
                         toggle=True,
                         icon_only=True,
                         )

        tow_row = column.row()
        tow_row.operator(asset.LoadAsset.bl_idname,
                         icon='FILE_REFRESH',
                         text='',
                         )
        tow_row.operator(asset.RefreshAsset.bl_idname,
                         icon='ASSET_MANAGER',
                         text='',
                         )
        tow_row.operator(asset.RefreshIcon.bl_idname,
                         icon='PHYSICS',
                         text='',
                         )

        ro = column.row(align=True)
        ro.prop(self, 'space_size')
        ro.prop(self, 'split_size')

    def filter_child_folder(self, items, blt_flag):
        """过滤显示子文件夹
        """
        init_flag = True  # 是否已经有了flag的

        if not blt_flag:
            blt_flag = [0] * len(items)
            init_flag = False

        for index, item in enumerate(items):
            is_show = (
                    blt_flag[index] and item.is_show) if init_flag else item.is_show
            blt_flag[index] = self.bitflag_filter_item if is_show else 0
        return blt_flag

    def filter_items(self, _context, data, prop):
        from bpy.types import UI_UL_list

        items = getattr(data, prop)
        flt_new_order = []

        name_flags = UI_UL_list.filter_items_by_name(self.filter_name, self.bitflag_filter_item, items, 'name',
                                                     reverse=self.use_filter_name_reverse)

        folder_flags = self.filter_child_folder(items, name_flags)
        return folder_flags, flt_new_order


class AssetItems(UIList):
    bl_idname = 'UI_UL_DRAW_RENDER_MASTER_ASSET_ITEMS'

    icon_size: FloatProperty()
    scale_y: FloatProperty()

    def draw_item(self,
                  context: 'bpy.context',
                  layout: 'bpy.types.UILayout',
                  data: 'AnyType',
                  item: 'AnyType',
                  icon: int,
                  active_data: 'AnyType',
                  active_property: str,
                  index: int = 0,
                  flt_flag: int = 0):
        box = layout.box()
        box.scale_y = self.scale_y
        item.draw(box, self)

    def draw_filter(self, context: 'bpy.context', layout: 'bpy.types.UILayout'):
        column = layout.column()

        row = column.row(align=True)

        sub_row = row.row(align=True)
        sub_row.prop(self, 'filter_name')
        sub_row.prop(self, 'use_filter_invert',
                     icon='ARROW_LEFTRIGHT',
                     toggle=True,
                     icon_only=True,
                     )
        if not (self.use_filter_sort_lock and self.bitflag_filter_item):
            sub = sub_row.row(align=True)
            sub.prop(self, 'use_filter_sort_alpha',
                     toggle=True,
                     icon_only=True,
                     )

            icon = 'SORT_REVERSE' if (
                    self.bitflag_filter_item and self.use_filter_sort_reverse) else 'SORT_ASC'

            sub.prop(self, 'use_filter_sort_reverse',
                     icon=icon,
                     toggle=True,
                     icon_only=True,
                     )

        row = column.row()
        row.prop(self, 'icon_size')
        row.prop(self, 'scale_y')


class SelectedSet(UIList, Preferences):
    """绘制选择集"""
    bl_idname = 'UI_UL_DRAW_RENDER_MASTER_SELECTED_SET'

    def draw_item(self, context: 'Context', layout: 'UILayout', data: 'AnyType', item: 'AnyType', icon: int,
                  active_data: 'AnyType', active_property: str, index: int = 0, flt_flag: int = 0):
        item.draw(layout, self, index)


class_tuple = (
    AssetTree,
    # AssetItems, 替换使用grid_layout,
    SelectedSet,
)

reg_class, unreg_class = bpy.utils.register_classes_factory(class_tuple)


def register():
    reg_class()


def unregister():
    unreg_class()
